/**
 *	分页操作
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2023-07-19
 */


package com.framerock.db;

import com.framerock.server.Request;
import com.framerock.baselib.CallBack;
import com.framerock.baselib.Patter;
import com.framerock.baselib.Rock;

import java.util.ArrayList;
import java.util.Map;

public class DBLimit {

    protected Request mRequest;
    protected DBConn nDb;

    protected int totalCount = 0, page = 1, limit = 15;

    public DBLimit(DBConn dbs, Request req){
        this.nDb = dbs;
        mRequest = req;
    }

    /**
     * 翻页的处理
     * */
    public ArrayList<Map<String, String>> getData(String table, String where, String fields, String order, String groupby, String asqom, CallBack call)
    {
        page     = Integer.parseInt(mRequest.get("page", "1"));
        limit    = Integer.parseInt(mRequest.get("limit", "15"));
        String sort  = mRequest.get("sort");
        String dir   = mRequest.get("dir");
        if(!Rock.isEmpt(sort) && !Rock.isEmpt(dir) && Patter.iszgen(sort) && Patter.iszgen(dir)){
            order    = ""+asqom+"`"+sort+"` "+dir+"";
        }

        String sql   = "SELECT "+DB.chuliFields(fields)+" FROM "+DB.chuliTable(table)+" WHERE "+where+"";
        if(!Rock.isEmpt(groupby))sql+=" GROUP BY "+groupby+"";
        if(!Rock.isEmpt(order))sql+=" ORDER BY "+order+"";

        if(limit > 0) {
            sql += " LIMIT " + (page - 1) * limit + "," + limit + "";
            totalCount = this.nDb.getCount(table, where);
        }

        ArrayList<Map<String, String>> rows = this.nDb.getAll(sql, call);
        return rows;
    }

    public ArrayList<Map<String, String>> getData(String table, String where, String fields, String order, String groupby, CallBack call)
    {
        return getData(table, where, fields, order, groupby, "", call);
    }

    public int getCount()
    {
        return totalCount;
    }

    public ArrayList<Map<String, String>> getData(String table, String where, String fields, String order, String groupby)
    {
        return getData(table, where, fields, order, groupby, null);
    }

    public ArrayList<Map<String, String>> getData(String table, String where, String fields, String order)
    {
        return getData(table, where, fields, order, "", null);
    }

    public ArrayList<Map<String, String>> getData(String table, String where, String fields, String order, CallBack call)
    {
        return getData(table, where, fields, order, "", call);
    }

    public int getPage()
    {
        return this.page;
    }

    public int getLimit()
    {
        return this.limit;
    }
}
